package edu.yctc.weblog.controller.impl;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.code.kaptcha.impl.DefaultKaptcha;

import edu.yctc.weblog.constant.ResultCode;
import edu.yctc.weblog.constant.TemplatePath;
import edu.yctc.weblog.controller.KaptchaController;
import edu.yctc.weblog.exception.WeblogException;

@Controller
@RequestMapping(TemplatePath.S + TemplatePath.COMMON)
public class KaptchaControllerImpl implements KaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @GetMapping(TemplatePath.COMMON_KAPTCHA)
    @Override
    public void getDefaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        byte[] captchaOutputStream = null;
        ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String verifyCode = defaultKaptcha.createText();
            httpServletRequest.getSession().setAttribute("verifyCode", verifyCode);
            BufferedImage challenge = defaultKaptcha.createImage(verifyCode);
            ImageIO.write(challenge, "jpg", imgOutputStream);
            captchaOutputStream = imgOutputStream.toByteArray();
            httpServletResponse.setHeader("Cache-Control", "no-store");
            httpServletResponse.setHeader("Pragma", "no-cache");
            httpServletResponse.setDateHeader("Expires", 0);
            httpServletResponse.setContentType("image/jpeg");
            ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
            responseOutputStream.write(captchaOutputStream);
            responseOutputStream.flush();
            responseOutputStream.close();
        } catch (Exception e) {
            throw new WeblogException(ResultCode.ERROR_SYSTEM_EXCEPTION, e.getMessage());
        }

    }

}
